<!DOCTYPE html>
<html>

<head>
    <title> State的更新是异步和延迟的 </title>
    <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js" crossorigin></script>

    <style>
    </style>
</head>

<body>
    <div id="root"></div>
</body>

</html>

<script type="text/babel">
    var count = 1;

    class MyButton extends React.Component {
        constructor(props) {
            super(props);
            this.state = { num: 1 };
        }


        /*
        render:this.state.num=1
        onClickBtn,this.state.num[1]=1
        onClickBtn,this.state.num[2]=1
        render:this.state.num=2
        */
        // setState延迟更新
        onClickBtn() {
            console.log("onClickBtn,this.state.num[1]=" + this.state.num);
            this.setState({
                num: this.state.num + 1,
            });
            console.log("onClickBtn,this.state.num[2]=" + this.state.num);
        }

        // 使用SetTimeout，越过React的机制，令setState以同步形式出现
        /*
        render:this.state.num=1
        onClickBtn,this.state.num[1]=1
        onClickBtn,this.state.num[2]=2
        render:this.state.num=2
      */
        onClickBtn2() {
            setTimeout(() => {
                console.log("onClickBtn,this.state.num[1]=" + this.state.num);
                this.setState({
                    num: this.state.num + 1,
                });
                console.log("onClickBtn,this.state.num[2]=" + this.state.num);
            }, 0);

        }


        render() {
            console.log("render:this.state.num=" + this.state.num);
            return (
                <p style={{ backgroundColor: "#ff0000", with: "100px", height: "50px" }
                } type="primary" onClick={this.onClickBtn2.bind(this)} > Click this button,{this.state.num} </p >
            );
        }
    }
    ReactDOM.render(<MyButton />, document.getElementById('root'));
</script>